template.defaults.imports.splitImages = function (imgsStr) {
    var imgs = imgsStr.split(',');
    template.defaults.imports.imgs = imgs;
};

template.defaults.imports.getVideoInfo = function (videoId) {
    $.ajaxSettings.async = false;
    $.get('/listSnapshots',{
        videoId:videoId,
    },function(result){
        if (result.code == 100){
            var url = result.data.MediaSnapshot.Snapshots.Snapshot[0].Url;
            $.get('/getPlayInfo?videoId=' + videoId,function(result){
                var playVideo = '';
                for (var i = 0;i < result.data.length; i++){
                    if (result.data[i].Format == 'mp4'){
                        playVideo = result.data[i].PlayURL;
                        break;
                    }
                }
                template.defaults.imports.video = {
                    playUrl:playVideo,
                    imgUrl:url
                };
                $.ajaxSettings.async = true;
            });
        }
    });
};

template.defaults.imports.CountdownTime = function (factEndDate) {
    var timestamp = (new Date()).valueOf();
    return factEndDate - timestamp;
};

template.defaults.imports.TimestampToTime = function (timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes();
    return Y + M + D + h + m ;
};

template.defaults.imports.ellipsisName = function (name) {
    var strLen = name.length;
    if (strLen > 2){
        name = name.substr(1); //删除第一个字符
        name = name.substr(0, name.length - 1);
        return '*' + name + '*';
    } else if (strLen > 1){
        return name.substr(0, 1) + '*';
    } else {
        return name;
    }
};

template.defaults.imports.sendTime = function (createDate) {
    var timestamp = (new Date()).valueOf();
    var diffiTime = timestamp - createDate;
    //计算天
    var day = Math.floor(diffiTime / (1000 * 60 * 60 * 24));
    var surplus = diffiTime % (1000 * 60 * 60 * 24);
    var hour = Math.floor(surplus / (1000 * 60 * 60));
    surplus = surplus % (1000 * 60 * 60);
    var minute = Math.floor(surplus / (1000 * 60));
    return (day ? day + '天' : '') + (hour ? hour + '小时' : '') + (minute ? minute + '分' : '') + '前';
};

//查询商品详情
var productDetail = {};
$.post('/antique/api/mallProduct/web/query', {
    /* global getCookie visitUrl*/
    token: getCookie('token'),
    /* global id */
    id: id
}, function (result) {
    var _result = result;
    /* global template */
    var html = template('detail', result);
    document.getElementById('detail-content').innerHTML = html;
    productDetail = result.data;

    //设置分享
    $.post('/antique/api/wxApi/getticket', {
        url: window.location.href
    }, function (result) {
        //access_token = result.data.access_token;
        wx.config({
            debug: false,
            appId: result.data.appid,
            timestamp: result.data.timestamp,
            nonceStr: result.data.noncestr,
            signature: result.data.signature,
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'onMenuShareTimeline', 'onMenuShareAppMessage','onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'
            ]
        });
        wx.ready(function () {
            wx.checkJsApi({
                jsApiList: [
                    'onMenuShareTimeline', 'onMenuShareAppMessage','onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'
                ],
                success: function (res) {
                    //alert(JSON.stringify(res));
                    //alert(JSON.stringify(res.checkResult.getLocation));
                    if (res.checkResult.getLocation == false) {
                        alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
                        return;
                    } else {
                        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，
                        // 则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                        //分享到朋友圈
                        wx.onMenuShareTimeline({
                            title:'【' + productDetail.name + '】' + '【' + productDetail.sizeDesc + '】' + productDetail.detailsDesc, // 分享标题
                            link:window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl:productDetail.coverImage, // 分享图标
                            success: function () {
                                // 用户点击了分享后执行的回调函数
                                console.log("11");
                            },
                        });
                        //分享给朋友
                        wx.onMenuShareAppMessage({
                            title:'【' + productDetail.name + '】' + '【' + productDetail.sizeDesc + '】' + productDetail.detailsDesc, // 分享标题
                            link:window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: productDetail.coverImage, // 分享图标
                            type: '', // 分享类型,music、video或link，不填默认为link
                            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                            success: function () {
                            // 用户点击了分享后执行的回调函数
                            }
                        });
                    }
                }
            });
        });
        wx.error(function (res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            alert("验证失败，请重试！");
            wx.closeWindow();
        });
    });

    $('.cdetail-top .cdetail-top-auth time[sign="unmake"]').each(function () {
        $(this).removeAttr('sign');
        /* global Countdown */
        Countdown($(this).attr('time'), $(this));
    });

    $(".swiper-container").swiper({
        loop: true
    });

    var images = result.data.showImages.split(',');
    $(".swiper-slide").click(function() {
        var index = $(this).data('swiper-slide-index');
        var playerContainer = $('<div></div>').attr('id','playerContainer').css({
            position:'fixed',
            width:'100%',
            height:'100%',
            display:'none',
            top: '0',
            zIndex:'9999'
        }).appendTo(window.document.body);
        if ($('.swiper-slide[data-swiper-slide-index="' + index + '"]').hasClass('video')){
            var playUrl = $('.swiper-slide[data-swiper-slide-index="' + index + '"]').attr('data-url');
            var player = new Aliplayer({
                "id": "playerContainer",
                "source": playUrl,
                "width": "100%",
                "height": "500px",
                "autoplay": true,
                "isLive": false,
                "rePlay": true,
                "playsinline": true,
                "preload": true,
                "controlBarVisibility": "hover",
                "useH5Prism": true
            }, function (player) {
                player._switchLevel = 0;
                console.log("播放器创建了。");
            });
            var closeVideo = $('<svg id="closeVideo" t="1552392959791" class="icon" style="width:0.8rem;height:0.8rem;position:absolute;top:0.1rem;right:0.1rem;cursor:pointer;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5486" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M512 32C246.4 32 32 246.4 32 512s214.4 480 480 480 480-214.4 480-480S777.6 32 512 32" fill="#FF2828" p-id="5487"></path><path d="M713.6 713.6c-12.8 12.8-35.2 12.8-48 0l-153.6-153.6-153.6 153.6c-12.8 12.8-35.2 12.8-48 0s-12.8-35.2 0-48l153.6-153.6-153.6-153.6c-12.8-12.8-12.8-35.2 0-48s35.2-12.8 48 0l153.6 153.6 153.6-153.6c12.8-12.8 35.2-12.8 48 0s12.8 35.2 0 48l-153.6 153.6 153.6 153.6c16 12.8 16 35.2 0 48z" fill="#FFFFFF" p-id="5488"></path></svg>');
            playerContainer.append(closeVideo).show();
            closeVideo.click(function(){
                var _parent = $(this).parent();
                player.stop();
                _parent.remove();
            });
        } else {
            var currentUrl = $('.swiper-slide[data-swiper-slide-index="' + index + '"] img').attr('data-url');
            for (var i = 0;i < images.length;i++){
                images[i] = images[i];
            }
            wx.previewImage({
                current: currentUrl, // 当前显示图片的http链接
                urls: images // 需要预览的图片http链接列表
            });
        }        
    });
    var shopId = $('input[name="shopId"]').val();

    $('#standard_offer_target').click(function(){
        $('#sendPrice').val('');
        $("#standard_offer").popup();
    });   

    //开始分享
    $('#share').click(function(){
        $("#copyTtml").text('复制链接');
         /* global isMiniProgram createCanvas */
         $("#shareBottom").popup();
        // if (!sharing){
        //     sharing = true;
        //     wx.onMenuShareTimeline({
        //         title: result.data.name, // 分享标题
        //         link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        //         imgUrl: result.data.coverImage, // 分享图标
        //         success: function () {
        //             // 用户点击了分享后执行的回调函数
        //             sharing = false;
        //         }
        //     });
        // }
    });
    //s生成分享图片
    $("#openqrPic").click(function(){  
        $("#sharePic").popup();
        $(".topReturn").hide();
        createCanvas(productDetail);
    });

    //开始举报
    $('#report_target').click(function(){
        $('textarea[name="report-content"]').val('');
        $("#report").popup();
    });
    $('#confirmReport').click(function(){
       var text = $('textarea[name="report-content"]').val();
       if(text.length >= 20 && text.length <= 200){
            $.post('/antique/api/mallComplaint/complaint', {
                /* global id */
                keyId: id,
                type:2,
                content:text,
                token:getCookie('token')
            },function(data){
                $.toast('举报成功，谢谢您对我们的支持!');
            });
       } else {
            $.toast('对不起，您输入的举报内容文字不在20-200个字内！请修改后上传。');
       }
    });
    $('textarea[name="report-content"]').keyup(function(e){
        var text = $(this).val();
        $('.weui-textarea-counter span').text(text.length);
        if(text.length < 20){
            $('.weui-textarea-counter span').removeClass('green').addClass('red');
        } else if(text.length > 200){
            $('.weui-textarea-counter span').removeClass('green').addClass('red');
        } else {
            $('.weui-textarea-counter span').removeClass('red').addClass('green');
        }
    });

    //查询用户的信息
    $.post('/antique/api/sysUser/query_user_by_userId',{
        userId:getCookie('userId')
    },function(result){
        //如果是管理员就可以进行推荐
        if(result.data.onlineManage == 1){
            $('#recommend').css('display','inline').click(function(){
                $.confirm("您确认要推荐该藏品吗?", "确认推荐?", function() {
                    $.post('/antique/api/mallProduct/manage/recommend_product',{
                        token:getCookie('token'),
                        id:id
                    },function(result){
                        $.toast('推荐成功!',1000);
                    });
                }, function() {
                    //取消操作
                });
            });

            $('#unrecommend').css('display','inline').click(function(){
                $.confirm("您确认要取消推荐该藏品吗?", "确认取消推荐?", function() {
                    $.post('/antique/api/mallProduct/manage/recommend_product',{
                        token:getCookie('token'),
                        id:id,
                        type:2
                    },function(result){
                        $.toast('取消推荐成功!',1000);
                    });
                }, function() {
                    //取消操作
                });
            });
        }
    });

    //渲染关注用户信息
    getFollowUsers();

    //查询最近的藏品及其专场信息
    function querypaimaiList(){
        $.post('/antique/api/mallProduct/web/query_list', {
            start: 0,
            limit: 10,
            queryType: 1,
            shopId:shopId
        }, function (result) {
            /* global template */
            var leftList = [];
            var rightList = [];
            if (result.data.list){
                for(var i = 0;i<result.data.list.length;i++){
                    if (i%2 == 0){
                        leftList.push(result.data.list[i]);
                    } else {                        
                        rightList.push(result.data.list[i]);
                    }
                }
            }

            if(result.data.list && result.data.list.length > 0){
                /* global template */
                document.getElementById('paimai-left-list-content').innerHTML = template('paimai-left-list', {list:leftList});
                document.getElementById('paimai-right-list-content').innerHTML = template('paimai-right-list', {list:rightList}); 
                $('.weipai-list .lot .info .price .time time[sign="unmake"]').each(function () {
                    $(this).removeAttr('sign');
                    /* global Countdown */
                    Countdown($(this).attr('time'), $(this));
                });
            } else {
                $('.weui-navbar__item').eq(0).hide();
                $('#tab1').hide();
            }
        });
    }

    function queryyijiaList(){
        $.post('/antique/api/mallProduct/web/query_list', {
            start: 0,
            limit: 10,
            queryType: 2,
            shopId:shopId
        }, function (result) {
            /* global template */
            var leftList = [];
            var rightList = [];
            if (result.data.list){
                for(var i = 0;i<result.data.list.length;i++){
                    if (i%2 == 0){
                        leftList.push(result.data.list[i]);
                    } else {                        
                        rightList.push(result.data.list[i]);
                    }
                }
            }

            if(result.data.list && result.data.list.length > 0){
                /* global template */
                document.getElementById('yijia-left-list-content').innerHTML = template('yijia-left-list', {list:leftList});
                document.getElementById('yijia-right-list-content').innerHTML = template('yijia-right-list', {list:rightList}); 
                $('#tab2 .lot .info .price .time time[sign="unmake"]').each(function () {
                    $(this).removeAttr('sign');
                    /* global Countdown */
                    Countdown($(this).attr('time'), $(this));
                });
            } else {
                $('.weui-navbar__item').eq(1).hide();
                $('#tab2').hide();
            }
        });
    }

    function querySpecial(){
        $.post('/antique/api/mallAuction/web/query_list', {
            start: 0,
            limit: 10,
            source: 2,
            showProduct:1,
            shopId:shopId
        }, function (result) {
            if(result.data.list && result.data.list.length > 0){
                document.getElementById('zc-content').innerHTML = template('zc', result.data);
            } else {
                $('.weui-navbar__item').eq(2).hide();
                $('#tab3').hide();
            }
        });
    }

    querypaimaiList();
    queryyijiaList();
    querySpecial();
});

//查询出价记录
$.post('/antique/api/productBidLog/query_list', {
    /* global id */
    productId: id,
    start:0,
    limit:200,
    bidType:2
}, function (result) {
    $('#offerCount').text(result.data.list ? result.data.list.length : 0);
    /* global template */
    var html = template('cdetail-price-list', result);
    document.getElementById('cdetail-price-list-content').innerHTML = html;
});

$('#confirmPrice').click(function(){
    /* global isInteger */
    var sendPrice = parseInt($('#sendPrice').val());
    if (sendPrice && isInteger(sendPrice)){
        $.post('/antique/api/productBidLog/bid',{
            bidType:2,
            bidCount:1,
            bidPrice:$('#sendPrice').val(),
            productId:id,
            token:getCookie('token')
        },function(result){
            if(result.code != 1){
                $.toast("出价成功!", function() {
                    window.location.reload();
                });
            } else {
                $.toast(result.message,2000);
            }
        });
    } else {
        $.toast("必须输入数字", "forbidden");
    }
});

$('.cdetail-bottom .cdetail-icon-item').click(function(){
    $('.cdetail-bottom .cdetail-icon-item').removeClass('current');
    $(this).addClass('current');
});

$('#goshop').click(function(){
    visitUrl('/shop/detail?id=' + $('.cdetail-shop').attr('shopId'),true);
});

$.post('/antique/api/userProductCollection/check_collection',{
    productId:id,
    token:getCookie('token')
},function(result){
    var isColl = result.data.collection;
    if (isColl){
        $('.cdetail-bottom .cdetail-icon-item').eq(2).addClass('selected');
    } else {
        $('.cdetail-bottom .cdetail-icon-item').eq(2).removeClass('selected');
    }
});

$('.cdetail-bottom .cdetail-icon-item').eq(2).click(function(){
    if ($(this).hasClass('selected')){
        $(this).removeClass('selected');
        //取消收藏
        collProduct(false);
    } else {
        $(this).addClass('selected');
        //开始收藏
        collProduct(true);
    }
});

//私信聊天
$('.cdetail-bottom .cdetail-icon-item').eq(1).click(function(){
    var userId = $('input[name="userId"]').val();
    if(checkUserMe(userId)){
        $.toast('自己和自己不能聊天', "cancel");
    } else {
        visitUrl('/chat?charToUser=' + userId  + '&productId=' + id,true);
    }
});

function collProduct(isColl){
    $.post('/antique/api/userProductCollection/set_collection',{
        productId:id,
        operType:isColl ? 1 : 2,
        token:getCookie('token')
    },function(result){
        if(result.code != 1){
            if (isColl){
                $.toast('收藏成功!',1000);
                $('.cdetail-bottom .cdetail-icon-item').eq(2).addClass('selected');
                followUserCount(1);
            } else {
                $.toast('取消收藏成功!',1000);
                $('.cdetail-bottom .cdetail-icon-item').eq(2).removeClass('selected');
                followUserCount(-1);
            }
        } else {
            $('.cdetail-bottom .cdetail-icon-item').eq(2).removeClass('selected');
            $.toast(result.message,1000);
        }
        getFollowUsers();
    });
}
//增加访问足迹
$.post('/antique/api/userFootPrint/view_product',{
    productId:id,
    token:getCookie('token')
},function(){
    
});

//修改当前藏品时时显示关注数
function followUserCount(num){
    var collCount = parseInt($('#collCount').text());
    var currentCollCount = collCount + num;
    $('#collCount').text(currentCollCount);
}

/**读取关注用户信息 */
function getFollowUsers(){
    $.post('/antique/api/userProductCollection/query_user_list',{
        productId:id,
        token:getCookie('token'),
        start:0,
        limit:20
    },function(result){
        document.getElementById('followUsers-list-content').innerHTML = template('followUsers-list', {list:result.data?result.data.list:null});
    });
}